package com.qf.shop.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.qf.shop.entity.Goods;
import com.qf.shop.mapper.GoodsMapper;
import com.qf.shop.service.IGoodsService;
import com.qf.shop.vo.ExcelGoods;
import com.qf.shop.vo.GoodsId;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelGoodsListener extends AnalysisEventListener<ExcelGoods> {


    private IGoodsService goodsService;
    private GoodsMapper goodsMapper;


    // 表示每次读取两千条数据, 就往数据库写一次
    private Integer batch_size = 2000;

    private List<Goods> goodsList = new ArrayList<>(batch_size);

    public ExcelGoodsListener(IGoodsService goodsService,GoodsMapper goodsMapper) {
        this.goodsService = goodsService;
        this.goodsMapper = goodsMapper;
    }

    public ExcelGoodsListener(IGoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @Override
    public void invoke(ExcelGoods excelGoods, AnalysisContext analysisContext) {

        Date date = new Date();
        Goods goods = new Goods();

        goods.setType(excelGoods.getItemId());
        goods.setTitle(excelGoods.getGoodsName());
        goods.setStatus("1");
        GoodsId goodsId = goodsMapper.getGoodsId();
        goods.setGoodId(goodsId.getGoodsId()+1);
        goods.setPrice(excelGoods.getPrice());
        goods.setStock(excelGoods.getGoodsNumber());
        goods.setUpdateTime(date);
        goods.setCreateTime(date);

        goodsList.add(goods);

        if(goodsList.size() >= batch_size) {
            goodsService.batchInset(goodsList);
            // clear() 清空集合的数据, 释放内存.
            goodsList.clear();
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {


        // 因为数据刚刚 2000条
        if(goodsList.size() > 0) {
            goodsService.batchInset(goodsList);
            goodsList.clear();
        }

    }
}
